
import React, { useState, useRef, useEffect } from "react";
import './index.css'
interface BulletScreenProps {
  bulletList: string[];
}

interface BulletScreenState {
  bulletTracks: string[][][];
  animationTime: number;
}

const DEFAULT_RATIO = 260.67; // 默认的弹幕速度

function generateRandomString(length: number): string {
  let result = "";
  const characters =
    "阿斯利康等哈是老客户大剌剌我当前偶尔哈维爱唯欧的武器和科维奇金额和冷酷无情和";
  const charactersLength = characters.length;

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

// 假设bullets已经是一个字符串数组
const bullets: string[] = new Array(10)
  .fill(0)
  .map(() => generateRandomString(Math.random() * 10 + 5)); // 确保长度至少为5

const BulletScreen: React.FC<BulletScreenProps> = ({ bulletList }) => {
  const [bulletTracks, setBulletTracks] = useState<string[][][]>([]);
  const [animationTime, setAnimationTime] = useState(12);
  const trackRef = useRef<HTMLDivElement>(null);

  const shuffleArray = (array:any) => {
    const shuffledArray = array.slice();
    const random = function (min:any, max:any) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };
    for (let i = shuffledArray.length - 1; i > 0; i--) {
      const j = random(0, i);
      [shuffledArray[i], shuffledArray[j]] = [
        shuffledArray[j],
        shuffledArray[i],
      ];
    }
    return shuffledArray;
  };

  useEffect(() => {
    const shuffleTracks = new Array(3)
      .fill(0)
      .map((item) => shuffleArray(bulletList));
    setBulletTracks(shuffleTracks);
  }, [bulletList]);

  useEffect(() => {
    const trackElement = trackRef.current;
    if (trackElement) {
      const trackLength = trackElement.offsetWidth;
      const newAnimationTime = trackLength / DEFAULT_RATIO;
      setAnimationTime(newAnimationTime);
    }
  }, [bulletTracks]);

  return (
    <div className="bullet_container">
      {bulletTracks.map((track, trackIndex) => (
        <div className="double_track" key={trackIndex}>
          <div
            ref={trackRef}
            className="bullet_track"
            style={{
              top: `${trackIndex * 2}rem`,
              animationDuration: `${animationTime}s`,
            }}
          >
            {[...track, ...track].map((bullet, index) => (
              <span key={index} className="bullet" style={{ marginRight: 100 }}>
                {bullet}
              </span>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

const Demo: React.FC = () => {
  return (
    <div className="barrage_box" style={{ height: "10%" }}>
      <BulletScreen bulletList={bullets} />
    </div>
  );
};

export default Demo; // 如果你打算在其他地方导入Demo组件，请确保它被导出
